<?php

namespace app\common\model\room;

use app\common\library\Jcc;
use app\common\model\game\Groups;
use app\common\model\GoldLog;
use app\common\model\MoneyLog;
use app\common\model\User;
use app\common\model\user\Bindgame;
use think\Cache;
use think\Db;
use think\Exception;
use think\Model;


class Lists extends Model
{

    // 表名
    protected $table = 'room_lists';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'number',
        'create_text'
    ];

    /**
     * 房间变化监听
     * @param $members 房间内人员信息
     * @param $groups 群聊信息
     * @param $teamId 三方房间ID
     * @param $wxid 微信群ID
     * */
    public static function change($members, $groups, $teamId, $wxid, $uin, $fromname)
    {
        $room_id = self::where("team_id", $teamId)->value("id", 0);

        $inster_users = [];//新入房间用户
        $already_exist = [];//目前房间内正常用户
        foreach ($members as $vm) {
            $bind_where = [
                'game_id' => $groups['game_id'],
                'subarea_id' => $groups['subarea_id'],
                'game_number' => $vm['roleId']
            ];
            $user_id = Bindgame::where($bind_where)->value('user_id');
            if ($user_id) {//根据绑定信息查找用户
                $room_users = Users::where(['room_id' => $room_id, 'user_id' => $user_id])->find();
                $game_nickname = Bindgame::where($bind_where)->value("game_nickname");
                if (empty($game_nickname)) {
                    Bindgame::update([
                        "game_nickname" => $vm["nickname"],
                        "game_avatar" => $vm["headImage"]
                    ], $bind_where);
                }

                if (!$room_users) {//是否在房间内
                    $tickets = (new Groups())->deduction($user_id, $groups['id']);//门票money 服务费service
                    $all_tickets = $tickets['money'] + $tickets['service'];//总费用
                    $user_money = User::where('id', $user_id)->value('money', 0);
                    $user_gold = User::where('id', $user_id)->value('gold', 0);

                    if ($user_money < $all_tickets) {//对比余额
                        if ($user_gold < $all_tickets) {
                            $user_tickets = $user_money + $user_gold;
                            if ($user_tickets < $all_tickets) {
                                $insert_money = $user_money;
                                $insert_gold = $all_tickets - $user_money;
                                $inster_users[] = [
                                    "id" => $user_id, "money" => $insert_money, 'gold' => $insert_gold,
                                    "service" => $tickets['service'], 'all' => $all_tickets,
                                    "game_id" => Bindgame::where($bind_where)->value("id"),
                                    "currency_type" => 3
                                ];
                            } else {
                                $cache_name = "not_fund_{$user_id}_{$teamId}}";
                                if (Cache::has($cache_name)) {
                                    $is_fund = Cache::get($cache_name);
                                } else {
                                    $is_fund = 2;
                                    Cache::set($cache_name, 1);
                                }
                                $room_status = self::where("team_id", $teamId)->value("status");
                                if (isset($room_status) && $room_status == 0) {//房间存在且等待中
                                    $yue_buzu = $vm['nickname'] . "，余额不足，请检查一下余额是否充足，如果余额不足会导致本局战绩作废,奖励无法下发";
                                } else {
                                    $yue_buzu = $vm['nickname'] . "，创建房间失败，余额不足，请检查一下余额是否充足,";
                                }
                                if ($is_fund == 2) {
                                    Jcc::send_msg($wxid, $yue_buzu, $teamId);
                                }
                            }
                        } else {
                            $inster_users[] = [
                                "id" => $user_id, "money" => $tickets['money'], 'gold' => 0.00,
                                "service" => $tickets['service'], 'all' => $all_tickets,
                                "game_id" => Bindgame::where($bind_where)->value("id"),
                                "currency_type" => 2
                            ];
                        }
                    } else {
                        $inster_users[] = [
                            "id" => $user_id, "money" => $tickets['money'], 'gold' => 0.00,
                            "service" => $tickets['service'], 'all' => $all_tickets,
                            "game_id" => Bindgame::where($bind_where)->value("id"),
                            "currency_type" => 1
                        ];
                    }
                } else {
                    $already_exist[] = $user_id;
                }
            }
        }

        if (empty($inster_users) && $room_id == 0) {
            return ['code' => 0, "msg" => "房间创建失败"];
        }


        Db::startTrans();
        try {

            $time = time();
            $new = 0;
            if ($room_id == 0) {
                $link = "";
                switch ($groups['mode_id']) {
                    case 9:
                        $link = 'https://game.weixin.qq.com/cgi-bin/h5/static/contentcenter/home.html?wechat_pkgid=contentcenter_home&ssid=29&appid=wxb23e82d26e8ab140&&report_data="{"source_name":"金铲铲之战","source_id":"wxc3f2d27d4eb91269"}"&pass_data={"type":2,"message":"{\"teamId\":\"' . $teamId . '\",\"uin\":\"' . $uin . '\",\"isWatchMode\":\"F\",\"sceneType\":\"25\",\"setid\":8}"}#wechat_redirect';
                        break;
                    case 2:
                        $link = 'https://game.weixin.qq.com/cgi-bin/h5/static/contentcenter/home.html?wechat_pkgid=contentcenter_home&ssid=29&appid=wxb23e82d26e8ab140&&report_data={"source_name":"金铲铲之战","source_id":"wxc3f2d27d4eb91269"}&pass_data={\"teamId\":\"' . $teamId . '\",\"uin\":\"' . $uin . '\",\"isWatchMode\":\"F\",\"sceneType\":\"31\",\"setid\":9}"}#wechat_redirect';
                        break;
                }
                $room_id = Db::name('room_lists')->insertGetId([
                    "game_id" => $groups['game_id'], "subarea_id" => $groups['subarea_id'],
                    "modes_id" => $groups['mode_id'], "levels_id" => $groups['level_id'],
                    "team_id" => $teamId, 'createtime' => $time, 'updatetime' => $time,
                    "link" => $link
                ]);
                $new = 1;
            }

            foreach ($inster_users as $vu) {
                Users::create([
                    "room_id" => $room_id, "user_id" => $vu['id'],
                    "money" => $vu['money'], "service" => $vu['service'],
                    "game_id" => $vu['game_id'], "currency_type" => $vu['currency_type']
                ]);
                $already_exist[] = $vu['id'];
                $user = User::get($vu['id']);
                if ($user && $vu['all'] != 0) {//门票减额
                    switch ($vu['currency_type']) {
                        case 1:
                            $before = $user['money'];
                            $after = function_exists('bcadd') ? bcadd($user['money'], -$vu['all'], 2) : $user['money'] - $vu['all'];
                            $user->save(['money' => $after]);
                            MoneyLog::create([
                                "user_id" => $user['id'], "money" => -$vu['all'], 'before' => $before,
                                'after' => $after, "memo" => "金铲铲门票-房间:" . $room_id, "type" => 2
                            ]);
                            break;
                        case 2:
                            $before = $user['gold'];
                            $after = function_exists('bcadd') ? bcadd($user['gold'], -$vu['all'], 2) : $user['gold'] - $vu['all'];
                            $user->save(['gold' => $after]);
                            GoldLog::create([
                                "user_id" => $user['id'], "gold" => -$vu['all'], 'before' => $before,
                                'after' => $after, "memo" => "金铲铲门票-房间:" . $room_id, "type" => 3
                            ]);
                            break;
                        case 3:
                            $money_before = $user['money'];
                            $gold_before = $user['gold'];
                            $money_after = bcadd($user['money'], -$vu['money']);
                            $gold_after = bcadd($user['gold'], -$vu['gold']);

                            MoneyLog::create([
                                "user_id" => $user['id'], "money" => -$vu['money'], 'before' => $money_before,
                                'after' => $money_after, "memo" => "金铲铲门票-房间:" . $room_id, "type" => 2
                            ]);
                            GoldLog::create([
                                "user_id" => $user['id'], "gold" => -$vu['gold'], 'before' => $gold_before,
                                'after' => $gold_after, "memo" => "金铲铲门票-房间:" . $room_id, "type" => 3
                            ]);

                            $user->save(['money' => $money_after, 'gold' => $gold_after]);
                            break;
                    }

                }
            }

            $tuichu = Users::where(["room_id" => $room_id, "user_id" => ["NOT IN", $already_exist]])->select();

            foreach ($tuichu as $vt) {
                Users::destroy($vt['id']);
                $all = $vt['money'] + $vt['service'];
                $tuser = User::get($vt['user_id']);

                switch ($vt['currency_type']) {
                    case 1:
                        $before_t = $tuser['money'];
                        $after_t = function_exists('bcadd') ? bcadd($tuser['money'], $all, 2) : $tuser['money'] + $all;
                        $tuser->save(['money' => $after_t]);
                        MoneyLog::create([
                            "user_id" => $vt['user_id'], "money" => $all, 'before' => $before_t,
                            'after' => $after_t, "memo" => "金铲铲门票退还-房间:" . $room_id, "type" => 3
                        ]);
                        break;
                    case 2:
                        $before_t = $tuser['gold'];
                        $after_t = function_exists('bcadd') ? bcadd($tuser['gold'], $all, 2) : $tuser['gold'] + $all;
                        $tuser->save(['gold' => $after_t]);
                        GoldLog::create([
                            "user_id" => $vt['user_id'], "gold" => $all, 'before' => $before_t,
                            'after' => $after_t, "memo" => "金铲铲门票退还-房间:" . $room_id, "type" => 4
                        ]);
                        break;
                    case 3:
                        $gold = $vt['service'] + $vt['gold'];
                        $before_t_money = $tuser['money'];
                        $before_t_gold = $tuser['gold'];
                        $after_t_money = bcadd($tuser['money'], $vt['money'], 2);
                        $after_t_gold = bcadd($tuser['gold'], $gold, 2);
                        MoneyLog::create([
                            "user_id" => $vt['user_id'], "money" => $vt['money'], 'before' => $before_t_money,
                            'after' => $after_t_money, "memo" => "金铲铲门票退还-房间:" . $room_id, "type" => 3
                        ]);

                        GoldLog::create([
                            "user_id" => $vt['user_id'], "gold" => $gold, 'before' => $before_t_gold,
                            'after' => $after_t_gold, "memo" => "金铲铲门票退还-房间:" . $room_id, "type" => 4
                        ]);
                        break;
                }

            }
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            return ['code' => 0, 'msg' => $exception->getMessage()];
        }

        if ($new == 1) {
            $money = Db::name("game_levels")->where('id', $groups['level_id'])->value("money", 0);
            $mode_name = Db::name("game_modes")->where('id', $groups['mode_id'])->value("name", "");
            Jcc::send_msg($wxid, "@{$fromname} 创建比赛成功通知:你已成功创建了比赛[NO.{$room_id} {$mode_name} {$money}银币]", $teamId);
        }
        return ['code' => 1, "msg" => ""];
    }

    //房间解散
    public static function dissolve($teamId)
    {
        $room = self::where('team_id', $teamId)->find();
        if ($room) {
            Db::startTrans();
            try {
                $user = Users::where(["room_id" => $room->id])->select();
                foreach ($user as $vu) {
                    Users::destroy($vu['id']);
                    $all = $vu['money'] + $vu['service'];
                    $tuser = User::get($vu['user_id']);

                    switch ($vu['currency_type']) {
                        case 1:
                            $before_t = $tuser['money'];
                            $after_t = function_exists('bcadd') ? bcadd($tuser['money'], $all, 2) : $tuser['money'] + $all;
                            $tuser->save(['money' => $after_t]);
                            MoneyLog::create([
                                "user_id" => $vu['user_id'], "money" => $all, 'before' => $before_t,
                                'after' => $after_t, "memo" => "金铲铲门票退还-房间:" . $room->id, "type" => 3
                            ]);
                            break;
                        case 2:
                            $before_t = $tuser['gold'];
                            $after_t = function_exists('bcadd') ? bcadd($tuser['gold'], $all, 2) : $tuser['gold'] + $all;
                            $tuser->save(['gold' => $after_t]);
                            GoldLog::create([
                                "user_id" => $vu['user_id'], "gold" => $all, 'before' => $before_t,
                                'after' => $after_t, "memo" => "金铲铲门票退还-房间:" . $room->id, "type" => 4
                            ]);
                            break;
                        case 3:
                            $gold = $vu['service'] + $vu['gold'];
                            $before_t_money = $tuser['money'];
                            $before_t_gold = $tuser['gold'];
                            $after_t_money = bcadd($tuser['money'], $vu['money'], 2);
                            $after_t_gold = bcadd($tuser['gold'], $gold, 2);
                            MoneyLog::create([
                                "user_id" => $vu['user_id'], "money" => $vu['money'], 'before' => $before_t_money,
                                'after' => $after_t_money, "memo" => "金铲铲门票退还-房间:" . $room->id, "type" => 3
                            ]);

                            GoldLog::create([
                                "user_id" => $vu['user_id'], "gold" => $gold, 'before' => $before_t_gold,
                                'after' => $after_t_gold, "memo" => "金铲铲门票退还-房间:" . $room->id, "type" => 4
                            ]);
                            break;
                    }
//                    $before_t = $tuser['money'];
//                    $after_t = function_exists('bcadd') ? bcadd($tuser['money'], $all, 2) : $tuser['money'] + $all;
//                    $tuser->save(['money' => $after_t]);
//                    MoneyLog::create([
//                        "user_id" => $vu['user_id'], "money" => $all, 'before' => $before_t,
//                        'after' => $after_t, "memo" => "金铲铲门票退还", "type" => 3
//                    ]);
                }
                $room->status = 3;
                $room->save();
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                return ['code' => 0, "msg" => $exception->getMessage()];
            }

            return ['code' => 1, 'msg' => ''];
        } else {
            return ['code' => 0, 'msg' => '当前房间不存在'];
        }
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusList()
    {
        return ['0' => '等待中', '1' => '对战中', '2' => '已结束', 3 => '已解散'];
    }

    public function getNumberAttr($value, $data)
    {
        return Users::where(['room_id' => $data['id'], 'status' => 1])->count();
    }

    public function getCreateTextAttr($value, $data)
    {
        $value = $value ? $value : ($data['createtime'] ?? "");
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function game()
    {
        return $this->belongsTo('app\common\model\game\Lists', 'game_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function levels()
    {
        return $this->belongsTo('app\common\model\game\Levels', 'levels_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function modes()
    {
        return $this->belongsTo('app\common\model\game\Modes', 'modes_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function subarea()
    {
        return $this->belongsTo('app\common\model\game\Subarea', 'subarea_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
